<style>
    .ck-editor__editable_inline {
        height: 400px !important;
    }
</style>
<style>
    #toolbar {
        height: 30px;
        background-color: #fff;
        width: 100%;
        color: #fff;
        line-height: 30px;
    }

    #toolbar img {
        width: 20px;
        height: 20px;
        padding-top: 6px;
        padding-bottom: 4px;
        margin-left: 10px;
    }

    #toolbar img:hover {
        background: #EBEBEB;
        cursor: pointer;
    }

    #dialog {
        position: fixed;
        height: 360px;
        width: 600px;
        background: #FFFFFF;
        z-index: 5;
        left: 30%;
        border: 1px solid gray;
        top: 25%;
        display: none;
    }

    #cancel {
        border: 0px none #FFECEC;
        background: #999999;
        color: #FFFFFF;
        padding: 5px 15px;
        position: absolute;
        top: 8px;
        right: 100px;
    }

    #cancel:hover {
        background: #AAAAAA;
    }
</style>

<article class="cl pd-20">
    <form action="{:url('save')}" method="post" class="form form-horizontal" id="form-save">
        <input type="hidden" name="id" value="{$data['id']}">
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">
                <span class="c-red">*</span>栏目:</label>
            <div class="formControls col-xs-8 col-sm-6">
                <input type="hidden" name="cid" value="{$data['cid']}">
                {$category.name_en}
            </div>
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">
                <span class="c-red">*</span>标题:</label>
            <div class="formControls col-xs-8 col-sm-6">
                <input type="text" class="input-text" value="{$data.title}" placeholder="请填写标题" id="title" name="title">
            </div>
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">
                作者: </label>
            <div class="formControls col-xs-4 col-sm-2">
                <input type="text" class="input-text" value="{$data.writer}" placeholder="作者" id="writer" name="writer">
            </div>
            <label class="form-label col-xs-4 col-sm-2">
                来源:</label>
            <div class="formControls col-xs-4 col-sm-2">
                <input type="text" class="input-text" value="{$data.source}" placeholder="来源" id="source" name="source">
            </div>
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">
                发布时间: </label>
            <div class="formControls col-xs-4 col-sm-2">
                <input type="text" class="input-text" value="{$data.pubtime}" placeholder="作者" id="pubtime" name="pubtime">
            </div>
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">
                标题图：</label>
            <div class="formControls col-xs-6 col-sm-4">
                <input type="text" class="input-text" value="{$data.titlepic}" name="titlepic" id="titlepic">
                <div style="width: 160px;height: 160px;">
                    <a href="javascript:void(0);" onclick="uploadPicture()">
                        <img id="view-titlepic"
                            src="{$data.titlepic ? $data.titlepic : '/static/images/upload_picture.png'}" alt="标题图"
                            title="{$data.titlepic ? '更换' : '添加'}标题图" style="max-width: 160px;max-height: 160px;">
                    </a>
                </div>
            </div>
            <label class="form-label col-xs-2 col-sm-2">
                <a class="btn btn-success radius" href="javascript:uploadPicture();">{$data.titlepic ? '更换' :
                    '添加'}标题图</a></label>
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">
                关键词:</label>
            <div class="formControls col-xs-8 col-sm-6">
                <input type="text" class="input-text" value="{$data.keywords}" placeholder="关键词" id="keywords"
                    name="keywords">
                <span class="c-red">多个关键词用英文','分割</span>
            </div>
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">内容简介:</label>
            <div class="formControls col-xs-8 col-sm-6">
                <textarea name="summary" id="summary" cols="" rows="" class="textarea" placeholder="说点什么...最多输入500个字符"
                    datatype="*10-100" dragonfly="true" onKeyUp="textarealength(this,500)">{$data.summary}</textarea>
                <p class="textarea-numberbar">
                    <em class="textarea-length">0</em>/500
                </p>
            </div>
            <div class="col-3"> </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-4 col-sm-2">文章正文：</label>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-1 col-sm-2">补充按钮</label>
            <div class="formControls col-xs-11 col-sm-10">
                <div id="toolbar">
                    <img src="/static/images/online_image.png" id="image" title="网络图片" onclick="showDialog(0)" />
                    <img src="/static/images/movie.png" id="image" title="上传视频" onclick="showDialog(1)" />
                    <img src="/static/images/upload_file.png" id="image" title="上传附件" onclick="showDialog(2)" />
                </div>
            </div>
            <div class="formControls col-xs-11 col-sm-10  col-xs-offset-1 col-sm-offset-1">
                <div id="editor">{$data.content|raw}</div>
            </div>
        </div>
        <div class="row cl">
            <label class="form-label col-xs-2 col-sm-2">
                点击量：</label>
            <div class="formControls col-xs-4 col-sm-2">
                <input type="number" class="input-text" value="{$data.hits}" id="hits" name="hits"
                    style="width: 120px;">
            </div>
            <label class="form-label col-xs-2 col-sm-2">
                排序：</label>
            <div class="formControls col-xs-4 col-sm-2">
                <input type="number" class="input-text" value="{$data.sort}" id="sort" name="sort"
                    style="width: 120px;">
            </div>
        </div>
        <div class="row cl">
            <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3">
                <button type="button" class="btn btn-success radius" id="form-button-save">确&nbsp;定</button>
                <button type="button" class="btn btn-default radius" onclick="button_close();"
                    style="margin-left:20px;">返&nbsp;回</button>
            </div>
        </div>
    </form>
    <!-- 标题图上传 -->
    <div>
        <form id="form-upload_picture">
            <input type="file" hidden name="image" id="upload_picture">
        </form>
    </div>
</article>

<!-- 编辑器补充按钮 -->
<div id="dialog">
    <div style="position: absolute;height: 40px;width: 100%;background: #FFFFFF;border-bottom: 1px solid gray;">
        <span style="position: absolute;left: 10px;top: 10px;color: gray;" class="dialog-tilte">插入网络图片</span>
        <img src="/static/images/X.png"
            style="height: 25px;width: 25px;position: absolute;right: 10px;top: 10px;cursor: pointer;"
            onclick="f_cancel()" />
    </div>
    <!-- 网络图片 -->
    <div class="tab step0 active" style="margin-left:30px;margin-top:40px;">
        <form id="form-uploadurlimg" method="post" action="">
            <div class="row cl" style="margin-top:20px;">
                <div class="formControls">
                    <span class="c-red">*</span>图片要求: 格式 jpg,png,gif,jpeg,webp; 每张大小不超过4M.
                </div>
                <div class="col-3"> </div>
            </div>
            <div class="row cl" style="margin-top:10px;">
                <div class="formControls">
                    <span class="c-red">*</span>图片地址列表,一张图片一行
                </div>
                <div class="col-3"> </div>
            </div>
            <div class="row cl" style="margin-top:10px;">
                <div class="formControls">
                    <textarea class="textarea" style="width: 580px;height: 160px;text-align: left;" name="url_file"
                        id="url_file"></textarea>
                </div>
                <div class="col-3"> </div>
            </div>
            <div class="row cl" style="margin-top:10px;">
                <div class="formControls col-sm-6 col-xs-8 col-sm-offset-4 col-xs-offset-4">
                    <button type="button" class="btn btn-success radius" onclick="uploadUrlImg()">插入</button>
                </div>
            </div>
        </form>
    </div>
    <!-- 网络图片 -->
    <!-- 视频 -->
    <div class="tab step1" style="margin-left:30px;margin-top:50px;display: none;">
        <form id="form-uploadurlimg" method="post" action="">
            <div class="row cl" style="margin-top:30px;">
                <div class="formControls col-sm-10 col-xs-8">
                    <span class="c-red">*</span>视频要求: mp4,flv,mpeg,avi等常见网络视频格式; 每个不超过20M, 更大视频请FTP工具上传或使用外站链接.
                </div>
                <div class="col-3"> </div>
            </div>
            <div class="row cl" style="margin-top:10px;">
                <div class="formControls col-sm-10 col-xs-8">
                    <input type="file" name="upload_movie" id="upload_movie" value="">
                </div>
                <div class="col-3"> </div>
            </div>
            <div class="row cl" style="margin-top:10px;">
                <div class="formControls col-sm-6 col-xs-8 col-sm-offset-4 col-xs-offset-4">
                    <button type="button" class="btn btn-success radius" onclick="uploadMoive()">上传</button>
                </div>
            </div>
        </form>
    </div>
    <!-- 视频 -->
    <!-- 附件 -->
    <div class="tab step2" style="margin-left:30px;margin-top:50px;display: none;">
        <form id="form-uploadurlimg" method="post" action="">
            <div class="row cl" style="margin-top:30px;">
                <div class="formControls col-sm-10 col-xs-8">
                    <span class="c-red">*</span>文件要求: zip,doc,docx,xls,xlsx,pdf文件; 每个不超过10M, 更大文件请FTP工具上传或使用外站链接.
                </div>
                <div class="col-3"> </div>
            </div>
            <div class="row cl" style="margin-top:10px;">
                <div class="formControls col-sm-10 col-xs-8">
                    <input type="file" name="upload_file" id="upload_file" multiple value="">
                    <div class="progress">
                        <div></div>
                    </div>
                </div>
                <div class="col-3"> </div>
            </div>
            <div class="row cl" style="margin-top:10px;">
                <div class="formControls col-sm-6 col-xs-8 col-sm-offset-4 col-xs-offset-4">
                    <button type="button" class="btn btn-success radius" onclick="uploadFile()">上传</button>
                </div>
            </div>
        </form>
    </div>
    <!-- 附件 -->
    <div style="position: absolute;bottom: 1px;width: 100%;height: 40px;border-top: 1px solid gray;">
        <button type="button" id="cancel" onclick="f_cancel()">取消</button>
    </div>
</div>

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="/static/plugins/jquery.validation/1.14.0/jquery.validate.js"></script>
<script type="text/javascript" src="/static/plugins/jquery.validation/1.14.0/messages_zh.js"></script>
<script type="text/javascript" src="/static/plugins/jquery.validation/1.14.0/validate-methods.js"></script>
<script type="text/javascript" src="/static/plugins/ckeditor/ckeditor5/ckeditor.js"></script>
<script type="text/javascript">
    $(function () {
        ClassicEditor.create(document.querySelector('#editor'), {
            toolbar: {
                items: [
                    'sourceEditing', '|',
                    'bold', 'italic', 'strikethrough', 'underline', 'subscript', 'superscript', '|',
                    'heading', '|',
                    'fontfamily', 'fontsize', 'fontColor', 'fontBackgroundColor', 'highlight', '|',
                    '-',
                    'alignment', 'outdent', 'indent', '|',
                    'undo', 'redo', '|',
                    'link', 'imageUpload','imageInsert', 'insertTable', '|',
                    'code', 'codeBlock', 'blockQuote', '|',
                    'findAndReplace', 'horizontalLine', 'numberedList', 'bulletedList',
                ],
                shouldNotGroupWhenFull: true
            },
            licenseKey: '',
            //图片上传
            simpleUpload: {
                // The URL the images are uploaded to.
                uploadUrl: '/sys/file_manager/ckeditorUploadImage'
            },
            //自定义字体
            fontFamily: {
                options: [
                    'default',
                    '微软雅黑,Microsoft YaHei',
                    '新宋体,NSimSun',
                    '楷体_GB2312,KaiTi_GB2312',
                    '黑体,SimHei',
                    '隶书,LiSu',
                    '幼园,YouYuan',
                    'Blackoak Std',
                    'Arial',
                    'Georgia',
                    'Tahoma',
                    'Trebuchet MS',
                    'verdana',
                ]
            },
            mediaEmbed: {   // 视频配置
                providers: [
                    {
                        name: 'myprovider',
                        url: [
                            /^suryee.*\.com.*\/(\w+)/,
                            /^www\.suryee.*/,
                            /^www\.bilibili.*/,
                            /(http|https):\/\/([\w.]+\/?)\S*/
                        ],
                        html: match => {
                            //获取媒体url
                            const input = match['input'];
                            return (
                                `<video src="${input}" controls="controls" style=" width: 100%;height: 100%; "></video>`
                            );
                        }
                    }
                ]
            }
        }).then(editor => {
            window.editor = editor;
        }).catch(error => {
            console.error('Oops, something went wrong!');
            console.error('Please, report the following error on https://github.com/ckeditor/ckeditor5/issues with the build id and the error stack trace:');
            console.warn('Build id: z4e2d8lqju9w-6lwv92tbu4hm');
            console.error(error);
        });
    })

    // window.editor.editing.view.change(writer => {
    //     writer.setStyle('height', '400px', editor.editing.view.document.getRoot());
    // });

    // 标题图上传
    const file = document.querySelector('input[type="file"]');

    function uploadPicture() {
        // file模拟input点击事件
        var evt = new MouseEvent("click", {
            bubbles: false,
            cancelable: true,
            view: window,
        });
        file.dispatchEvent(evt, uploadfn());
    }

    function uploadfn() {
        file.oninput = function () {
            if (file.files && file.files[0]) {
                var formData = new FormData();
                formData.append("upload_file", file.files[0]);
                $.ajax({
                    url: '{:url("/sys/file_manager/uploadImage")}',
                    type: "post",
                    data: formData,
                    processData: false, // 告诉jQuery不要去处理发送的数据
                    contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                    dataType: 'json',
                    success: function (res) {
                        // console.log(res);
                        var img = res.data.filename;
                        $("#view-titlepic").attr('src', img);
                        $("#titlepic").val(img);
                        layer.msg(res.msg, {
                            icon: 1,
                            time: 1000
                        });
                    },
                    error: function (res) {
                        layer.msg(res.msg, {
                            icon: 5,
                            time: 1000
                        });
                        return false;
                    },
                    complete: function () {
                        document.getElementById('form-upload_picture').reset();
                    }
                });
            }
        }
    }

    // 补充按钮
    //插入图片弹窗取消
    function f_cancel() {
        $('#dialog').hide();
    }
    //显示弹窗
    function showDialog(mod) {
        console.log(mod);
        if (mod == 1) {
            $(".tab").css("display", 'none');
            $(".step" + mod).css("display", 'block');
        } else if (mod == 2) {
            $(".tab").css("display", 'none');
            $(".step" + mod).css("display", 'block');
        } else {
            $(".tab").css("display", 'none');
            $(".step0").css("display", 'block');
        }
        $('#dialog').show();
    }

    function uploadUrlImg() {
        var url_file = $("#url_file").val();
        if (url_file == '') {
            layer.msg("请选择要上传的地址", {
                icon: 6,
                time: 1000
            });
            return false;
        } else {
            $.ajax({
                url: '{:url("file_manager/uploadurlimg")}',
                type: 'post',
                data: {
                    url_file: url_file
                },
                dataType: "json",
                success: function (res) {
                    // console.log(res);
                    if (res.code == 0) {
                        res.data.forEach(element => {
                            var obj = document.createElement('img') // 添加的内容可以自定义， 这里以添加图片为例
                            obj.setAttribute('src', element)
                            // console.log(obj);
                            var viewFragment = window.editor.data.processor.toView(obj.outerHTML);
                            var modelFragment = window.editor.data.toModel(viewFragment);
                            window.editor.model.insertContent(modelFragment, editor.model.document.selection);
                        });
                        $("#url_file").val("");
                        f_cancel();
                    } else {
                        layer.msg(res.msg, {
                            icon: 5,
                            time: 1000
                        });
                        return false;
                    }
                }
            });
        }
    }

    function uploadMoive() {
        let uploadFile = $("#upload_movie").get(0).files;
        // console.log(uploadFile);
        if (uploadFile == undefined || uploadFile == null) {
            layer.msg("请选择文件", { icon: 5, time: 1000 });
            return false;
        }

        let formData = new FormData();

        formData.append('upload_movie', uploadFile[0]);

        $.ajax({
            url: '{:url("file_manager/uploadMoive")}',
            type: 'post',
            dataType: 'json',
            data: formData,
            processData: false,
            contentType: false,
            success: function (res) {
                console.log(res);
                if (res.code == 0) {
                    var origin = window.location.origin
                    var url = origin + res.data;
                    var obj = document.createElement('video')
                    console.log(url);

                    var obj = document.createElement('figure');
                    obj.setAttribute('class', "media");
                    var vobj = document.createElement('oembed');
                    vobj.setAttribute('url', url);
                    obj.appendChild(vobj);

                    var viewFragment = window.editor.data.processor.toView(obj.outerHTML);
                    var modelFragment = window.editor.data.toModel(viewFragment);
                    window.editor.model.insertContent(modelFragment, editor.model.document.selection);

                    $("#upload_movie").val("");
                    f_cancel();
                } else {
                    layer.msg(res.msg, {
                        icon: 5,
                        time: 1000
                    });
                    return false;
                }
            }
        });
    }


    function uploadFile() {
        let uploadFile = $("#upload_file").get(0).files;
        // console.log(uploadFile);
        if (uploadFile == undefined || uploadFile == null) {
            layer.msg("请选择文件", { icon: 5, time: 1000 });
            return false;
        }

        if (uploadFile.length > 20) {
            layer.msg("最多20个文件", { icon: 5, time: 1000 });
            return false;
        }

        let formData = new FormData();

        for (let i = 0; i < uploadFile.length; i++) {
            formData.append('upload_file[]', uploadFile[i]);
        }

        $.ajax({
            url: '{:url("file_manager/uploadFile")}',
            type: 'post',
            dataType: 'json',
            data: formData,
            processData: false,
            contentType: false,
            xhr: function () {
                var xhr = new XMLHttpRequest();
                //使用XMLHttpRequest.upload监听上传过程，注册progress事件，打印回调函数中的event事件
                xhr.upload.addEventListener('progress', function (e) {
                    // console.log(e);
                    //loaded代表上传了多少
                    //total代表总数为多少
                    var progressRate = (e.loaded / e.total) * 100 + '%';

                    //通过设置进度条的宽度达到效果
                    $('.progress > div').css('width', progressRate);
                })

                return xhr;
            },
            success: function (res) {
                // console.log(res);
                if (res.code == 0) {
                    res.data.forEach(element => {
                        var url = element.url
                        var filename = element.filename

                        var obj = document.createElement('a')
                        obj.setAttribute('href', url)
                        obj.setAttribute('style', "color:blue")
                        obj.innerText = filename

                        var brobj = document.createElement('br')
                        obj.appendChild(brobj)
                        console.log(obj)

                        var viewFragment = window.editor.data.processor.toView(obj.outerHTML)
                        var modelFragment = window.editor.data.toModel(viewFragment)
                        window.editor.model.insertContent(modelFragment, editor.model.document.selection)
                    });

                    $("#upload_file").val("");
                    f_cancel();
                } else {
                    layer.msg(res.msg, {
                        icon: 5,
                        time: 1000
                    });
                    return false;
                }
            }
        });
    }

    function validator(params) {
        return $("#form-save").validate({
            debug: true,
            rules: {
                title: {
                    required: true,
                }
                , summary: {
                    maxlength: 500,
                }
                , sort: {
                    max: 99
                }
                , cid: {
                    required: true
                }
            },
            messages: {
                title: {
                    required: "标题不能为空"
                }
                , cid: {
                    required: "栏目不能为空"
                }
            }
        });
    }

    $("#form-button-save").click(function () {
        if (!validator().form()) {
            return false
        }

        const content = window.editor.getData();
        $("<input/>").attr("type", "hidden").attr("name", "content").val(content).appendTo($("#form-save"));
        var data = $("#form-save").serializeArray();

        const edit_type = $("input[name='id']").val() == 0 ? 0 : 1;  // 0新增, 1 修改
        // console.log(edit_type);
        $.ajax({
            type: 'POST',
            url: '{:url("/sys/article_en/save")}',
            data: data,
            dataType: 'json',
            success: function (res) {
                // console.log(res);
                if (res.code == 0) {
                    if (edit_type == 1) {
                        layer.msg(res.msg, { icon: 1, time: 500 }, function () {
                            // parent.location.reload(); // 父页面刷新
                            // var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                            // parent.layer.close(index);
                            window.location.href = '/sys/article/index';  // 返回列表页
                        });
                    } else {
                        layer.msg(res.msg, { icon: 1, time: 500 }, function () {
                            // window.location.reload(); // 子页面刷新
                            document.getElementById('form-save').reset(); // 表单重置
                            $("#titlepic").val('');
                            window.editor.setData('');
                        });
                    }
                } else {
                    layer.msg(res.msg, {
                        icon: 5,
                        time: 1000
                    });
                    return false;
                }
            }
        })
    });

    function button_close(){
        window.location.href = '/sys/article_en/index.html';
    }
</script>